/*
 * ============================================================================
 *                   GNU Lesser General Public License
 * ============================================================================
 *
 *
 *
 * 
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 * 
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 * 
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307, USA.
 * 
 *
 *
 */
package rad.framework.jmx;

import java.util.List;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import javax.interceptor.InvocationContext;
import javax.management.InstanceAlreadyExistsException;
import javax.management.MBeanServer;
import javax.management.MBeanServerFactory;
import javax.management.ObjectName;

import org.jboss.seam.Component;
import org.jboss.seam.log.LogProvider;
import org.jboss.seam.log.Logging;

/**
 * @author boudyacho
 */
public class MBeanInterceptor {

	private static final LogProvider log = Logging
			.getLogProvider(MBeanInterceptor.class);

	@PostConstruct
	public void postConstruct(InvocationContext ctx) throws Exception {
		ObjectName objectName = getObjectName(ctx);
		try {
			getServer().registerMBean(getComponent(ctx), objectName);
			log.debug("Created: " + objectName);
		} catch (InstanceAlreadyExistsException e) {
		}
	}

	@PreDestroy
	public void preDestroy(InvocationContext ctx) throws Exception {
		ObjectName objectName = getObjectName(ctx);
		log.debug("Destroying: " + objectName);
		getServer().unregisterMBean(objectName);
	}

	protected MBeanServer getServer() {
		List<MBeanServer> servers = MBeanServerFactory.findMBeanServer(null);
		return servers.get(0);
	}

	protected ObjectName getObjectName(InvocationContext ctx) throws Exception {
		MBean annotation = ctx.getTarget().getClass()
				.getAnnotation(MBean.class);
		return new ObjectName(annotation.objectName());
	}

	protected Object getComponent(InvocationContext ctx) throws Exception {
		return Component.getInstance(ctx.getTarget().getClass());
	}
}